package com.pandarouter;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ConnectException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;

public class SSH implements Runnable{
	private String path = "";
	private String result="";
	private Session session =null;
	private ChannelExec openChannel =null;
	private Boolean connected = false;
	private String connect(String host,String user,String psw,int port){
		try {
			JSch jsch=new JSch();
		    session = jsch.getSession(user, host, port);
		    java.util.Properties config = new java.util.Properties();
		    config.put("StrictHostKeyChecking", "no");
		    session.setConfig(config);
		    session.setPassword(psw);
		    session.connect();
		    result = exec("pwd");
		    connected = true;
		} catch (JSchException e) {
			if(e.getMessage().equals("java.net.ConnectException: Connection refused: connect"))
				System.out.println("ssh connect failed,please check your ssh parameters and try again.");
			else if(e.getMessage().equals("Auth fail"))
				System.out.println("ssh auth failed,please check your ssh parameters and try again.");
			else
				e.printStackTrace();
				connected = false;
		}finally{
		}
		return result;
	}
	private String exec(String command){
		String result = "";
		try {
			openChannel = (ChannelExec) session.openChannel("exec");
		    openChannel.setCommand(command);
		    openChannel.connect();
		    InputStream in = openChannel.getInputStream();
		    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
		    String buf = null;
		    while ((buf = reader.readLine()) != null) {
	    		result= result.equals("")?new String(buf.getBytes("gbk"),"UTF-8"):result +"\r\n"+ new String(buf.getBytes("gbk"),"UTF-8");
		    }
		}catch(JSchException e){
			result = "-2";
		}catch(IOException e){
			e.printStackTrace();
		}
		return result;
	}
	public String exec2(String host,String user,String psw,int port,String command){
		try {
			JSch jsch=new JSch();
		    session = jsch.getSession(user, host, port);
		    java.util.Properties config = new java.util.Properties();
		    config.put("StrictHostKeyChecking", "no");
		    session.setConfig(config);
		    session.setPassword(psw);
		    session.connect();
		    openChannel = (ChannelExec) session.openChannel("exec");
		    openChannel.setCommand(command);
		    int exitStatus = openChannel.getExitStatus();
		    System.out.println(exitStatus);
		    openChannel.connect();  
		    InputStream in = openChannel.getInputStream();
		    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
		    String buf = null;
		    while ((buf = reader.readLine()) != null) {
		    		result+= new String(buf.getBytes("gbk"),"UTF-8")+"    <br>\r\n";
		    }
		}catch(ConnectException e){
			result = "-1";
		}catch (JSchException | IOException e) {
		    result=e.getMessage();
		}finally{
			if(openChannel!=null&&!openChannel.isClosed()){
				openChannel.disconnect();
			}
			if(session!=null&&session.isConnected()){
				session.disconnect();
			}
		}
		return result;
	}
	private void sendResult(String command,String path,String result){
		List<NameValuePair> sshResult = new ArrayList<NameValuePair>();
		sshResult.add(new BasicNameValuePair("X_REQUESTED_WITH","XMLHttpRequest"));
		sshResult.add(new BasicNameValuePair("action","updateResult"));
		sshResult.add(new BasicNameValuePair("command",command));
		sshResult.add(new BasicNameValuePair("path",path));
		sshResult.add(new BasicNameValuePair("result",result));
		String tString =Req.HttpPost(Worker.ssh_remoteUrl, sshResult);
		System.out.println(tString);
	}
	@Override
	public void run() {
		path = connect(Worker.sshHost, Worker.sshUser, Worker.sshPwd, Worker.sshPort);
		if(connected)
			sendResult("pwd",path,path);
		System.exit(0);
		while(connected){
			try{
				Thread.sleep(500);
			}catch(Exception e){
				
			}
			
		}
	}
}
